import time
from datetime import datetime, timedelta

from info import db
from info.common import user_login_data, img_upload
from info.constants import ADMIN_USER_PAGE_MAX_COUNT, ADMIN_NEWS_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.modules.admin import admin_blu
from flask import render_template, g, request, current_app, redirect, url_for, session, abort, jsonify

# 后台登陆
from info.utils.response_code import RET, error_map


@admin_blu.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        # 如果用户已经存在，直接重定向到后台首页
        user_id = session.get("user_id")
        is_admin = session.get("is_admin")
        if user_id and is_admin:
            return redirect(url_for("admin.index"))

        return render_template("admin/login.html")

    # post处理
    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不完整")

    # 根据参数取出用户模型
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据错误")

    if not user:
        return render_template("admin/login.html", errmsg="管理员不存在")

    # 密码校验
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="用户名/密码错误")

    # 用session保存用户登陆的状态
    session["user_id"] = user.id
    session["is_admin"] = True

    # 登陆成功，重定向到后台首页
    return redirect(url_for("admin.index"))


# 后台退出登陆
@admin_blu.route('/logout')
def logout():
    session.pop("is_admin", None)
    session.pop("user_id", None)
    return redirect(url_for("admin.login"))


# 后台首页
@admin_blu.route('/index')
@user_login_data
def index():
    return render_template("admin/index.html", user=g.user.to_dict())


# 用户统计
@admin_blu.route('/user_count')
def user_count():
    # 1.用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin != True).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 2.月新增人数
    mon_count = 0
    # 获取当前日期
    t = time.localtime()
    # 构建目标日期字符串 2018-10-01
    date_mon_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 将日期字符串 转为 日期 对象
    date_mon = datetime.strptime(date_mon_str, "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin != True, User.create_time >= date_mon).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 3.日新增人数
    day_count = 0
    # 构建目标日期字符串 2018-10-01
    date_day_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    # 将日期字符串 转为 日期 对象
    date_day = datetime.strptime(date_day_str, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin != True, User.create_time >= date_day).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 4.获取最近30天的日注册人数
    active_count = []  # 定义1个空列表,用来保存30注册的人数
    active_time = []  # 定义一个空列表  用来记录每天的注册人数
    for i in range(0, 30):
        # begin_date=date_day  #当天0点
        # end_date=date_day+timedelta(days=1)  #次日0点
        # begin_date = date_day-timedelta(days=i)
        # end_date = date_day + timedelta(days=1)-timedelta(days=i)
        begin_date = date_day - timedelta(days=i)
        end_date = date_day + timedelta(days=1 - i)
    try:
        # 每天注册人数:注册日期>=当前点,<次日点
        one_day_count = User.query.filter(User.is_admin != True, User.create_time >= begin_date,
                                          User.create_time < end_date).count()
        active_count.append(one_day_count)
        # 将日期对象 转为 日期字符串
        one_day_str = begin_date.strftime("%Y-%m-%d")
        active_time.append(one_day_str)

    except BaseException as e:
        current_app.logger.error(e)

    # 5.列表反转
    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,  # 每天注册数量
        "active_time": active_time
    }

    return render_template("admin/user_count.html", data=data)


# 用户列表查询
@admin_blu.route('/user_list')
def user_list():
    # 获取页码
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)
    user_list = []
    cur_page = 1
    total_page = 1
    # 查询所有用户信息  指定当前页码  按照收藏时间倒序
    try:
        pn = User.query.filter(User.is_admin == False).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)
        user_list = [user.to_admin_dict() for user in pn.items]
        cur_page = pn.page
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    data = {
        "user_list": user_list,
        "cur_page": cur_page,
        "total_page": total_page
    }

    # 收藏页面使用后端渲染, 需要将收藏的新闻传入模板
    return render_template("admin/user_list.html", data=data)


# 显示新闻审核列表
@admin_blu.route('/news_review')
def news_review():
    # 获取页码
    p = request.args.get("p", 1)
    # 获取查询关键字
    keyword = request.args.get("keyword")
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)
    news_list = []
    cur_page = 1
    total_page = 1

    # 如果设置了关键字,添加关键字过滤条件
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))

    # 查询所有新闻  指定当前页码
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)
        news_list = [news.to_review_dict() for news in pn.items]
        cur_page = pn.page
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "news_list": news_list,
        "cur_page": cur_page,
        "total_page": total_page
    }

    # 收藏页面使用后端渲染, 需要将收藏的新闻传入模板
    return render_template("admin/news_review.html", data=data)


# 显示新闻审核详情
@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 根据新闻id取出该新闻详情
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    if not news:
        return abort(404)

    return render_template("admin/news_review_detail.html", news=news.to_dict())


# 提交审核
@admin_blu.route('/news_review_action', methods=["POST"])
def news_review_action():
    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    reason = request.json.get("reason")

    # 参数校验
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 根据新闻id取出新闻
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 根据行为修改新闻状态
    if action == "accept":
        news.status = 0
    else:
        news.status = -1
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        news.reason = reason
    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 显示新闻版式编辑列表
@admin_blu.route('/news_edit')
def news_edit():
    # 获取页码
    p = request.args.get("p", 1)
    # 获取查询关键字
    keyword = request.args.get("keyword")
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)
    news_list = []
    cur_page = 1
    total_page = 1

    # 如果设置了关键字,添加关键字过滤条件
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))

    # 查询所有新闻  指定当前页码
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)
        news_list = [news.to_review_dict() for news in pn.items]
        cur_page = pn.page
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "news_list": news_list,
        "cur_page": cur_page,
        "total_page": total_page
    }

    # 收藏页面使用后端渲染, 将所有新闻传入模板
    return render_template("admin/news_edit.html", data=data)


# 新闻版式编辑详情
@admin_blu.route('/news_edit_detail/<int:news_id>')
def news_edit_detail(news_id):
    # 根据新闻id取出该新闻详情
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    if not news:
        return abort(404)

    # 查询所有的扥类,传入模板
    categories = []
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        # 取新闻属于那个分类
    category_list = []  # 定义一个空列表,用来存放所属类的新闻信息
    for category in categories:
        is_selected = False
        category_dict = category.to_dict()  # 转为字典类型
        if category.id == news.category_id:
            is_selected = True
        category_dict["is_selected"] = is_selected
        category_list.append(category_dict)  # 添加对应分类的新闻到类中

    # 删除"最新"分类
    if len(category_list):
        category_list.pop(0)

    return render_template("admin/news_edit_detail.html", news=news.to_dict(), category_list=category_list)


# 提交编辑
@admin_blu.route('/news_edit_detail', methods=["POST"])
def news_edit_action():
    # 获取参数
    news_id = request.form.get("news_id")
    category_id = request.form.get("category_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.form.get("index_image")

    # 参数校验
    if not all([news_id, category_id, title, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 格式转换
    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 取出新闻模型
    try:
        news = News.query.get(news_id)
        category = Category.query.get(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news or not category:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 修改新闻模型
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    if index_image:
        # 上传图片到文件服务器
        img_bytes = index_image.read()
        try:
            file_name = img_upload(img_bytes)
            news.index_image_url = QINIU_DOMIN_PREFIX + file_name
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 修改/添加分类
@admin_blu.route('/news_type', methods=["GET", "POST"])
def news_type():
    if request.method == "GET":
        categories = []
        # 根据分类id取出该分类的名称
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except BaseException as e:
            current_app.logger.error(e)

        return render_template("admin/news_type.html", categories=categories)

    # post处理
    id= request.json.get("id")
    name=request.json.get("name")

    if not name:
        return  render_template(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 根据id判断修改还是新增
    if id:
        try:
            id=int(id)
        except BaseException as e:
            current_app.logger.error(e)
            return render_template(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        # 取出分类模型
        try:
            category=Category.query.get(id)
        except BaseException as e:
            current_app.logger.error(e)

        if not category:
            return render_template(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        # 修改名称
        category.name=name

    else:
        new_category=Category(name=name)
        db.session.add(new_category)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
